#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. All Rights Reserved.

__author__ = 'dazza@google.com (Darryl Cain)'

import urllib
import datetime

import controllers

tables = {
  'qld': 'query=select+col0,+col1,+col2,+col3+from+391778+&o=kml&g=col0'
}

def loadKml(id):
  if not id in tables:
    return None

  url = urllib.urlopen('http://google.com/fusiontables/exporttable?' + tables[id])
  return url.read()

def updateKml(id):
  from google.appengine.api import memcache
  memcache.set('kmlproxy_' + id, loadKml(id))

def showKml(id):
  from google.appengine.api import memcache
  return memcache.get('kmlproxy_' + id)

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class UpdatePage(webapp.RequestHandler):
  def get(self):
    updateKml(self.request.get('table'))
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write('OK')

class ShowPage(webapp.RequestHandler):
  def get(self):
    controllers.cached_response(self.response, duration=300)
    self.response.headers['Content-Type'] = 'application/vnd.google-earth.kml+xml'
    self.response.out.write(showKml(self.request.get('table')))

application = webapp.WSGIApplication([('/ftkml/update__', UpdatePage),
                                      ('/ftkml/', ShowPage)], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
